package com.kfm.dao;

import com.kfm.model.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 对 user 数据库表的操作
 */
public class UserDao {

    public List<User> selectAll() {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from users";
        List<User> query = null;
        try {
            query = queryRunner.query(getConn(), sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return query;

    }

    public User selectByUsernameAndPassword(String username, String password) {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from users where name = ? and password = ?";
        try {
            return queryRunner.query(getConn(), sql, new BeanHandler<>(User.class), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


    private Connection getConn() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/kfm", "root", "");
    }
}
